<template>
    <div class="home-video-detail" v-loading="loading">
        <div class="top-flex-box">
            <div class="left-flex-box">
                <div class="show-video-box">
                    <video
                        v-if="detail.link"
                        controls="controls"
                        autoplay="autoplay"
                        class="video"
                        :src="detail.link">
                    </video>
                    <span v-else>暂无视频，请点击下方按钮上传</span>
                </div>
                <uploadVideo :url="detail.link" :storageid="detail.storageId" @change="changeVideo" :noUploadVideo="$route.query.id"/>
            </div>
            <div class="right-flex-box">
                <el-form
                    :model="detail"
                    :rules="rules"
                    :hide-required-asterisk="true"
                    ref="detail"
                    label-width="140px">
                    <el-form-item label="封面" prop="cover">
                        <uploadOwnImg v-model="detail.cover" :needTransform="1"/>
                    </el-form-item>
                    <el-form-item label="标题" prop="title">
                        <el-input type="textarea" v-model="detail.title"></el-input>
                    </el-form-item>
                    <el-form-item label="投放时间" prop="_time" v-if="!infinite">
                        <el-date-picker
                            v-model="detail._time"
                            type="datetimerange"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
                        </el-date-picker>
                    </el-form-item>

                    <el-form-item label="无限期投放">
                        <el-switch
                            @change="switchChange"
                            v-model="infinite"
                            active-color="#13ce66"
                        >
                        </el-switch>
                    </el-form-item>

                    <el-form-item label="最短播放时长" prop="durationMin">
                        <el-input-number v-model="detail.durationMin" controls-position="right" :min="1"></el-input-number> 秒
                    </el-form-item>
                    <el-form-item label="关联游戏" prop="gameId">
                        <el-select
                            style="width:100%;"
                            v-model="detail.gameId"
                            clearable
                            filterable
                            :filter-method="filterMethod"
                            :loading="gameLoading"
                            @change="gameChange"
                            placeholder="请输入并选择游戏">
                            <el-option
                                v-for="item in gameList"
                                :key="item.gameid"
                                :label="item.appName"
                                :value="item.gameid">
                                    <span style="float: left">
                                        <span>{{ item.appName }}</span>
                                        <span v-if="item.status === -1" style="color:red;font-size:12px;margin:0 5px;">下架</span>
                                    </span>
                                    <span style="float: right; color: #8492a6; font-size: 13px">{{ item.gameid }}</span>
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="视频来源">
                        <el-input type="text" v-model="detail.videoSource" style="width:300px;"></el-input>
                    </el-form-item>
                    <el-form-item label="状态" prop="adStatus">
                        <el-radio-group v-model="detail.adStatus">
                            <el-radio :label="1">上架</el-radio>
                            <el-radio :label="0">下架</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
            </div>
        </div>

        <div class="sumbmit-box">
            <el-button style="width:150px;" size="small" @click="goback">取 消</el-button>
            <el-button style="width:150px;" size="small" type="primary" @click="saveVideo" v-if="detail.bid">保 存</el-button>
            <el-button style="width:150px;" size="small" type="success" @click="submitForm" v-else>新 建</el-button>
        </div>
    </div>
</template>

<script>
export default {
    data () {
        return {
            loading: false,
            gameLoading: false,
            gameList: [],
            detail: {
                adStatus: 1,
                bid: null,
                cover: '',
                durationMin: 10,
                endTime: '',
                gameId: '',
                gameName: '',
                link: '',
                startTime: '',
                title: '',
                _time: [],
                videoSource: null
            },
            infinite: false, // 是否是无限期
            rules: {
                title: [
                    { required: true, message: '请输入标题', trigger: 'blur' }
                ],
                durationMin: [
                    { required: true, message: '请输入最短播放时长', trigger: 'blur' }
                ],
                // _time: [
                //     { type: 'date', required: true, message: '请选择投放时间', trigger: 'change' }
                // ],
                gameId: [
                    { required: true, message: '请关联游戏', trigger: 'change' }
                ]
            }
        }
    },
    created () {
        if (this.$route.query.id) {
            this.getDetail()
        }
        if (this.$route.query.gameid) {
            this.detail.gameid = this.$route.query.gameid
        }
        if (this.$route.query.name) {
            this.detail.gameName = this.$route.query.name
        }
    },
    methods: {
        // 获取视频详情
        async getDetail () {
            this.loading = true
            let res = await this.$http.get('/ad/adVideoInfo', {
                params: {
                    bid: this.$route.query.id
                }
            })
            if (res.code === '0') {
                if (res.data.gameName && res.data.gameId) {
                    this.getAllGameList(res.data.gameName)
                }
                if (res.data.startTime && res.data.endTime) {
                    if (res.data.startTime === '2020-01-01 00:00:00' && res.data.endTime === '2999-01-01 23:59:59') {
                        res.data._time = []
                        this.infinite = true
                    } else {
                        res.data._time = [res.data.startTime, res.data.endTime]
                    }
                } else {
                    res.data._time = []
                }
                this.detail = res.data
            } else {
                this.$message({
                    type: 'error',
                    message: res.desc
                })
            }
            this.loading = false
        },

        // 查询游戏
        filterMethod (res) {
            clearTimeout(this.timerId)
            if (!res) {
                this.gameLoading = false
                return
            }
            this.gameLoading = true
            this.timerId = setTimeout(() => {
                this.getgameList(res)
            }, 1000)
        },

        async getgameList (keyword) {
            let params = {
                keyword,
                pageIndex: 1,
                pageNum: 100
            }
            let res = await this.$http.post('/home/findGames', params)
            if (res.code === '0') {
                this.gameList = res.data
            } else {
                this.$message({
                    type: 'error',
                    message: '系统异常，请稍后再试'
                })
            }
            this.gameLoading = false
        },

        // 查询所有游戏
        async getAllGameList (keyword) {
            let params = {
                keyword,
                pageIndex: 1,
                pageNum: 10
            }
            let res = await this.$http.post('/game/findGames', params)
            if (res.code === '0') {
                this.gameList = res.data
            } else {
                this.$message({
                    type: 'error',
                    message: '系统异常，请稍后再试'
                })
            }
            this.gameLoading = false
        },

        gameChange (val) {
            this.gameList.forEach(item => {
                if (item.gameid === val) {
                    this.detail.gameName = item.appName
                }
            })
        },

        // switchChange选择无限期投放时间
        switchChange (val) {
            if (val) {
                this.detail._time = ['2020-01-01 00:00:00', '2999-01-01 23:59:59']
            } else {
                this.detail._time = []
            }
        },

        // 新建 更改视频
        async saveVideo () {
            if (!this.detail.link) {
                this.$message({
                    type: 'error',
                    message: '请上传视频后保存！'
                })
                return
            }
            if (this.loading) return
            this.loading = true
            if (this.detail._time && this.detail._time.length) {
                this.detail.startTime = this.detail._time[0]
                this.detail.endTime = this.detail._time[1]
            } else {
                // 未选择时间 默认为无限期投放
                this.detail._time = ['2020-01-01 00:00:00', '2999-01-01 23:59:59']
                this.detail.startTime = this.detail._time[0]
                this.detail.endTime = this.detail._time[1]
                this.infinite = true
            }
            let params = JSON.parse(JSON.stringify(this.detail))
            delete params._time
            try {
                let res = await this.$http.post('/ad/saveUpdateVideo', params)
                if (res.code === '0') {
                    this.$message({
                        type: 'success',
                        message: '保存成功'
                    })
                    this.detail.bid = res.data
                } else {
                    this.$message({
                        type: 'error',
                        message: res.desc
                    })
                }
                this.loading = false
            } catch (error) {
                this.$message({
                    type: 'error',
                    message: '网络异常，请稍后再试'
                })
                this.loading = false
            }
        },

        submitForm () {
            this.$refs.detail.validate((valid) => {
                if (valid) {
                    this.saveVideo()
                } else {
                    return false
                }
            })
        },

        // 返回
        goback () {
            this.$router.go(-1)
        },

        // 上传视频组建交互
        changeVideo (url, duration, storageid, cover, size, mp4Url) {
            this.detail.link = url || this.detail.link
            this.detail.storageId = storageid || this.detail.storageId
            this.detail.cover = cover || this.detail.cover
        }
    },
    components: {
        // uploadVideo
    },

    watch: {
        detail: {
            handler: function (val) {
                if (val.cover) {
                    this.$refs.detail.validateField('cover', (valid) => {
                        if (valid) {
                        } else {
                            return false
                        }
                    })
                }
            },
            deep: true
        }
    }
}
</script>

<style lang="scss" scoped>
    .home-video-detail {
        .top-flex-box {
            display: flex;
            .left-flex-box {
                width: 400px;
                padding: 0 20px;
                .show-video-box {
                    height: 640px;
                    // background-color: #000000;
                    border: 1px dashed #cccccc;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    .video {
                        width: 100%;
                        max-height: 100%;
                        outline: none;
                    }
                }
            }
            .right-flex-box {
                flex: 1;
                .user-msg-box {
                    display: flex;
                    align-items: center;
                    .user-icon {
                        width: 45px;
                        height: 45px;
                        border-radius: 50%;
                        margin-right: 10px;
                        overflow: hidden;
                        > img {
                            width: 100%;
                            height: 100%;
                        }
                    }
                }
            }
        }

        .sumbmit-box {
            width: 500px;
            margin: 30px auto 0;
            display: flex;
            align-items: center;
            justify-content: space-around;
        }

        .go-game-detail {
            font-size: 12px;
            color: #409EFF;
            cursor: pointer;
        }
    }
</style>
